import './css/index.scss';
import styles from './css/home.less';
import React, { useRef, useEffect, useState } from 'react';
import { useDispatch, useSelector, useHistory } from 'umi';
import { ICarsHome, ICarBrand } from '@/utils/interface';
import { getBaojia } from '../services/index'
import { Drawer, Button } from 'antd';
import Fastclick from 'fastclick'; //fastclick 解决移动端click事件延迟300ms
import LazyLoad from 'react-lazyload'; //图片懒加载

const Home: React.FC = () => {
  //使用useHistory
  const histort = useHistory();
  // 解决点击事件延迟300毫秒的问题
  (Fastclick as any).attach(document.body);
  // 通过useDispatch拿到派发redux的dispatch
  // 作用：共享状态，返回Redux的store中对dispatch的引用，可执行redux中的方法
  const dispatch = useDispatch();
  const [title, setTitle] = useState<string>('');

  const [CarSeries, setCarSeries] = useState<number>(0);
  const box = useRef(null);
  const wrap = useRef(null);
  const pop = useRef(null);
  const [moves, setMoves] = useState<number>();
  const [moven, setMoven] = useState<number>();

  // 数据解构,获取下拉列表的数据
  const { carBrandList, obj } = useSelector((models: any) => {
    return { ...models.cars };
  });

  //数据解构

  useEffect(() => {
    dispatch({
      type: 'cars/getCarsHome',
    });
  }, []);


  // 点击左侧每一个品牌，弹出右侧抽屉
  function popup(value: ICarsHome) {
    // 当前点击的元素是未知的，加个active属性
    ((pop.current as unknown) as HTMLElement).classList.add('active');
    setTitle(value.Name);

    dispatch({
      type: 'cars/getCarBrand',
      payload: value.MasterID,
    });
  }
  //点击右边的字母
  function right(e: React.MouseEvent<HTMLDivElement>) {
    const id = (e.target as HTMLElement).dataset.id; //当前点击元素的id
    const dom = document.getElementById(id as string); //获取左边对应的该id的整个元素对象
    // scrollTop() 方法返回或设置匹配元素的滚动条的垂直位置
    // obj.offsetTop 指 obj 距离上方或上层控件的位置
    ((wrap.current as unknown) as HTMLElement).scrollTop = (dom as HTMLElement).offsetTop;
    //    console.log(id,dom)
  }

  // 当按下手指时，触发ontouchstart；
  function start(e: React.TouchEvent<HTMLDivElement>) {
    // e.touches[0].clientX  手指横坐标
    const moves = e.touches[0].clientX;
    // const moven = ((e.target as unknown) as HTMLElement).offsetLeft;
    setMoves(moves);
    // setMoven(moven);
  }
  // 当移动手指时，触发ontouchmove；
  function move(e: React.TouchEvent<HTMLDivElement>) {
    const dis = e.touches[0].clientX - (moves as number);
    setCarSeries(dis);
    if (dis >= 120) {
      ((pop.current as unknown) as HTMLElement).style.transform = `matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ${dis}, 0, 0, 1)`;
    }
  }
  // 当移走手指时，触发ontouchend。
  function end(e: React.TouchEvent<HTMLDivElement>) {
    if (CarSeries >= 120) {
      ((pop.current as unknown) as HTMLElement).classList.remove('active');
      ((pop.current as unknown) as HTMLElement).style.transform = `matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)`;
    }
  }

  //跳详情
  const goDetail = (item: any) => {
    // console.log(item)
    getBaojia(item.SerialID).then(res => {
      // console.log(res.data)
      let date=res.data
      histort.push({ pathname: '/detail', state: { date } })
    })
  }

  return (
    <div className={styles.home} ref={wrap}>
      <ul className={styles.left}>
        {/* Object.keys()方法将返回由键组成的数组 ["A","B",...,"Z"]*/}
        {Object.keys(obj).map((item) => {
          return (
            <div key={item} id={item} ref={box}>
              <h2> {item}</h2>
              {obj[item].map((value: ICarsHome, index: number) => {
                return (
                  <ul key={index}>
                    <li>
                      <LazyLoad overflow={true}>
                        <img src={value.CoverPhoto} alt=""  referrerPolicy="no-referrer" />
                      </LazyLoad>
                      <span onClick={() => popup(value)}>{value.Name}</span>
                    </li>
                  </ul>
                );
              })}
            </div>
          );
        })}
      </ul>
      <div className={styles.right}>
        <div>
          <span>#</span>
        </div>
        <div>
          {Object.keys(obj).map((item) => {
            return (
              <div key={item} data-id={item} onClick={right}>
                <span data-id={item}>{item}</span>
              </div>
            );
          })}
        </div>
      </div>
      {/* 右侧弹出层 */}
      <div
        className={styles.popup}
        ref={pop}
        onTouchStart={start}
        onTouchMove={move}
        onTouchEnd={end}
      // onClick={}
      >
        {carBrandList.map((item: any, index: number) => {
          return (
            <div key={index} >
              <p className={styles.carBranUlP}>{item.GroupName}</p>
              {item.GroupList?.map((item: any) => {
                return (
                  <div key={item.SerialID} className={styles.SerialID} onClick={() => { goDetail(item) }}>
                    <img src={item.CoverPhoto} alt=""  referrerPolicy="no-referrer" />
                    <div>
                      <p className={styles.OneP}>{item.AliasName}</p>
                      <p className={styles.TwoP}>{item.DealerPrice}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          );
        })}
        <div className={styles.flex}></div>
      </div>
    </div>
  );
};

export default Home;
